package com.dsg.controller.oil;


import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dsg.aspect.NoRepeatSubmit;
import com.dsg.common.constants.MessageConstants;
import com.dsg.common.dto.AjaxResult;
import com.dsg.common.util.SingletonLoginUtils;
import com.dsg.common.util.UUIDGenerator;
import com.dsg.common.util.toolbox.StringUtil;
import com.dsg.controller.base.BaseController;
import com.dsg.entity.oil.DsgOilData;
import com.dsg.entity.system.DsgSysFile;
import com.dsg.service.oil.IDsgOilDataService;
import com.dsg.service.system.IDsgSysFileService;
import com.dsg.util.RRException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 入油数据汇总 前端控制器
 * </p>
 *
 * @author system
 * @since 2020-06-30
 */
@RestController
@RequestMapping("/oil/dsgOilData")
@Slf4j
@Api(description = "入油数据汇总")
public class DsgOilDataController extends BaseController {

    @Autowired
    private IDsgOilDataService dsgOilDataService;

    @Autowired
    private IDsgSysFileService dsgSysFileService;

    /**
     * 查询列表（分页）
     *
     * @param dsgOilData
     * @return
     */
    @GetMapping(value = "/list")
    @ApiOperation("查询列表（分页）")
    public AjaxResult list(DsgOilData dsgOilData) {
        Page page = getPage();  // 分页
        String sort = getParameter("sort");
        List<OrderItem> orderItemList = new ArrayList<>();
        if (StringUtil.isEmpty(sort)) {
//            orderItemList.add(new OrderItem().setColumn("OIL_COM").setAsc(false));
            orderItemList.add(new OrderItem().setColumn("CREATE_TIME").setAsc(false));
            page.setOrders(orderItemList);
        }
        dsgOilData.setEntCode(SingletonLoginUtils.getSystemEntCode());
        page = dsgOilDataService.selectByList(page, dsgOilData);
        AjaxResult ajaxResult = json(MessageConstants.SSO_STATUS_SUCCESS, page.getRecords(), (int) page.getTotal()); // 格式要返回的数据
        return ajaxResult;
    }

    /**
     * 查询单条数据
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/{id}/view")
    @ApiOperation("查询单条数据")
    public AjaxResult view(@PathVariable String id) {
        DsgOilData dsgOilData = dsgOilDataService.getById(id);
        return json(MessageConstants.SSO_STATUS_SUCCESS, dsgOilData);
    }

    /**
     * 新增
     *
     * @param dsgOilData
     * @return
     */
    @NoRepeatSubmit
    @PostMapping(value = "/add")
    @ApiOperation("新增")
    public AjaxResult add(@RequestBody DsgOilData dsgOilData) {
        dsgOilData.setOid(UUIDGenerator.getUUID());
        boolean flag = dsgOilDataService.save(dsgOilData);
        if (flag) {
            return json(MessageConstants.SSO_STATUS_SUCCESS, dsgOilData);
        } else {
            return result(MessageConstants.SSO_STATUS_FAIL);
        }
    }

    /**
     * 更新
     *
     * @param dsgOilData
     * @return
     */
    @NoRepeatSubmit
    @PutMapping(value = "/update")
    @ApiOperation("更新")
    public AjaxResult update(@RequestBody DsgOilData dsgOilData) {
        AjaxResult ajaxResult;
        boolean flag = dsgOilDataService.updateById(dsgOilData);
        if (flag) {
            ajaxResult = json(MessageConstants.SSO_STATUS_SUCCESS, dsgOilData);
        } else {
            ajaxResult = result(MessageConstants.SSO_STATUS_FAIL);
        }
        return ajaxResult;
    }

    /**
     * 批量删除
     *
     * @return
     */
    @DeleteMapping(value = "/delete")
    @ApiOperation("批量删除")
    public AjaxResult delete(@ApiParam(value = "id以，号分隔", name = "idList", required = true) @RequestParam String idList) {
        Boolean flag = dsgOilDataService.removeByIds(Arrays.asList(idList.split(",")));
        if (flag) {
            return result(MessageConstants.SSO_STATUS_SUCCESS);
        } else {
            return result(MessageConstants.SSO_STATUS_FAIL);
        }
    }

    /**
     * 批量修改處理狀態
     *
     * @return
     */
    @PutMapping(value = "/updateHandleStatus")
    @ApiOperation("批量修改處理狀態")
    public AjaxResult updateHandleStatus(@ApiParam(value = "id以，号分隔", name = "idList", required = true) @RequestParam String idList) {
        dsgOilDataService.updateHandleStatus(idList);
        return result(MessageConstants.SSO_STATUS_SUCCESS);
    }

    /**
     * 下載
     *
     * @return
     */
    @GetMapping(value = "/downloadFile")
    @ApiOperation("下載")
    public void downloadFile(@ApiParam(value = "id以，号分隔", name = "idList", required = true) @RequestParam String idList,
                             HttpServletResponse response) throws Exception {
        DsgSysFile dsgSysFile = dsgSysFileService.getFile(idList);
        if (dsgSysFile != null) {
            DsgOilData dsgOilData = dsgOilDataService.getById(idList);
            byte[] bytes = dsgSysFile.getFileContent();
            OutputStream os = response.getOutputStream();
            response.setContentType("application/x-excel;charset=UTF-8");
            response.setHeader("Content-Length", "" + bytes.length);
            response.setHeader("Content-disposition", "attachment; filename=\"" + (dsgOilData.getBatchNo()) + ".xlsx\"");
            os.write(bytes);
            os.flush();
            os.close();
        } else {
            throw new RRException("文件不存在！");
        }
    }

    /**
     * 入油數據檢查
     *
     * @param dsgOilData
     * @return
     */
    @PutMapping(value = "/checkData")
    @ApiOperation("入油數據檢查")
    public AjaxResult checkData(@RequestBody DsgOilData dsgOilData) {
        if (StringUtil.isEmpty(dsgOilData.getOid())) {
            return setErrorJson("主鍵不能為空！");
        } else {
            return dsgOilDataService.checkData(dsgOilData);
        }
    }
}
